import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bean/binding_terminal_type.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/binding_terminal_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/binding_terminal_auto_switch_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_auto_onoff_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_auto_onoff_page_by_each_day.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_terminal_volume_dialog.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'bean/common_terminal_settings_response_bean.dart';
import 'new_terminal_list_view_model.dart';


/// 更多设置页面
class TerminalCommonSettingsPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "TerminalCommonSettingsPage";

  const TerminalCommonSettingsPage({Key key,}) : super(key: key);

  @override
  _TerminalCommonSettingsPageState createState() => _TerminalCommonSettingsPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(
      BuildContext context,) {
    return RouterUtils.routeForFutureResult(
      context,
      TerminalCommonSettingsPage(),
      routeName: TerminalCommonSettingsPage.ROUTER,
    );
  }
}

class _TerminalCommonSettingsPageState extends BaseState<TerminalCommonSettingsPage> {

  NewTerminalListViewModel _viewModel;
  CommonTerminalSettingsBean _settingsBean;
  DateTime _startDateTime;
  DateTime _endDateTime;
  String _week;
  @override
  void initState() {
    super.initState();
    _viewModel = NewTerminalListViewModel(this);
    _viewModel.getTerminalCommonSettings(context);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body:Column(
        children: [
          _toTopBarWidget(),
          Expanded(child: _toPlaceHolderWidget()),
        ],
      ),
    );
  }

  Widget _toInfoWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel.commonSettingsValueNotifier,
      builder: (BuildContext context, CommonTerminalSettingsBean settingsBean, Widget Child){
        _settingsBean = settingsBean;
        _startDateTime = _settingsBean.getStartOrEndTime(0);
        _endDateTime = _settingsBean.getStartOrEndTime(1);
        _week = _settingsBean.autoOnoffWeek;
        return Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(left: 15, right: 15),
              decoration: BoxDecoration(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  ///自动开关机
                  _toAutoOnOffWidget(),
                  ///音量设置
                  _toSetVolumeWidget(),
                  ///人脸识别
                  _toFaceRecognizeWidget(),
                ],
              ),
            ),
            Spacer(),
            // GestureDetector(
            //   onTap: ()async{
            //   },
            //   child: Container(
            //     alignment: Alignment.center,
            //     color: ThemeRepository.getInstance().getLineColor_3A3F50(),
            //     height: 50,
            //     padding: EdgeInsets.symmetric(horizontal: 15),
            //     child: Row(
            //       children: [
            //         Text(
            //           "可选择部分设备进行个性化设置",
            //           style: TextStyle(
            //               color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
            //               fontSize: 14
            //           ),
            //         ),
            //         Spacer(),
            //         Image.asset(
            //           "images/index_arrow_ico.png",
            //           width: 6,
            //         )
            //       ],
            //     ),
            //   ),
            // ),
          ],
        );
      },
    );

  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      title: "通用设置",
      isShowBack: true,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel
                .getTerminalCommonSettings(context),
            loadingOnClick: () => _viewModel
                .getTerminalCommonSettings(context),
            child: child,
          );
        },
        child: _toInfoWidget());

  }

  // void _toSetAutoOnOffTime()async{
  //   BindingTerminalAutoOffStatusType autoOffStatusType;
  //   Map<String, dynamic> resultMap =
  //       await BindingTerminalAutoSwitchDialog.navigatorPushDialog(
  //       context,
  //       _startDateTime,
  //       _endDateTime,
  //       false, hideBottom: true);
  //   if (resultMap == null || resultMap.isEmpty) {
  //     return;
  //   }
  //   _startDateTime =
  //   resultMap[BINDING_TERMINAL_POP_START_DATE_TIME_KEY];
  //   _endDateTime =
  //   resultMap[BINDING_TERMINAL_POP_END_DATE_TIME_KEY];
  //   autoOffStatusType =
  //   _startDateTime == null || _endDateTime == null
  //       ? BindingTerminalAutoOffStatusType.unSetting
  //       : BindingTerminalAutoOffStatusType.setting;
  //   //开关机时间
  //   String time = getAutoOffTimeStr();
  //   //autoOnoff 00未设置 01已设置
  //   String status = "01";
  //   if(StringUtils.isEmpty(time)){
  //     time = _settingsBean.autoOnoffTime;
  //     status = "00";
  //   }
  //   _viewModel.saveCommonSettingsByAutoOnOff(context, time, status, "1,2,3,4,5", () {
  //     _viewModel.getTerminalCommonSettings(context);
  //   });
  // }

  ///定时开关机
  Widget _toAutoOnOffWidget(){
    String autoOnOffTime = getWeekAutoOnOffTimeStr();
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        if(StringUtils.isEmpty(autoOnOffTime) || ("00" == _settingsBean?.comAutoSwitch?.autoOnoff)){
          return;
        }
        SetAutoOnOffByEachDayPage.navigatorPush(context, _settingsBean?.comAutoSwitch, (comAutoSwitchBean){
          setState(() {
            _settingsBean?.comAutoSwitch = comAutoSwitchBean;
          });
          _viewModel.getTerminalCommonSettings(context);
        },
        callback: (){
          _viewModel.getTerminalCommonSettings(context);
        });
        
        // SetAutoOnOffPage.navigatorPushDialog(context, _startDateTime,
        //     _endDateTime, _week, (time, week){
        //       String status = "01";
        //       if(StringUtils.isEmpty(time)){
        //         time = _settingsBean.autoOnoffTime;
        //         week = _settingsBean.autoOnoffWeek;
        //         status = "00";
        //       }
        //       _viewModel.saveCommonSettingsByAutoOnOff(context, time, status, week, () {
        //         _viewModel.getTerminalCommonSettings(context);
        //       });
        //     });
        // _toSetAutoOnOffTime();
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            Text(
              "自动开关机",
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                  fontSize: 14
              ),
            ),
            Spacer(),
            Visibility(
              visible: StringUtils.isNotEmpty(autoOnOffTime) && ("01" == _settingsBean?.comAutoSwitch?.autoOnoff),
              child: Row(
                children: <Widget>[
                  Text(
                    autoOnOffTime,
                    style: TextStyle(
                        // color:ThemeRepository.getInstance()
                        //     .getTextEditHintColor_3A3F50(),
                        color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                        fontSize: 14
                    ),
                  ),
                  SizedBox(width: 10,),
                  Image.asset(
                    "images/index_arrow_ico.png",
                    width: 6,
                  )
                ],
              ),
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                //auto_onoff 00未设置 01已设置
                if(StringUtils.isNotEmpty(autoOnOffTime)){
                  _settingsBean?.comAutoSwitch?.autoOnoff = "01";
                  _viewModel.saveAutoOnOffByWeek(context,
                      _settingsBean?.comAutoSwitch,  () {
                    _viewModel.getTerminalCommonSettings(context);
                    //打开之后进入设置页面
                    SetAutoOnOffByEachDayPage.navigatorPush(context, _settingsBean?.comAutoSwitch, (comAutoSwitchBean){
                      setState(() {
                        _settingsBean?.comAutoSwitch = comAutoSwitchBean;
                      });
                      _viewModel.getTerminalCommonSettings(context);
                    },
                        callback: (){
                          _viewModel.getTerminalCommonSettings(context);
                        });
                  }, noToast: true);
                }else{

                  SetAutoOnOffByEachDayPage.navigatorPush(context, _settingsBean?.comAutoSwitch, (comAutoSwitchBean){
                    setState(() {
                      _settingsBean?.comAutoSwitch = comAutoSwitchBean;
                    });
                    _viewModel.getTerminalCommonSettings(context);
                  },
                      callback: (){
                        _viewModel.getTerminalCommonSettings(context);
                      });

                  // SetAutoOnOffPage.navigatorPushDialog(context, _startDateTime,
                  //     _endDateTime, _week, (time, week){
                  //       String status = "01";
                  //       if(StringUtils.isEmpty(time)){
                  //         time = _settingsBean.autoOnoffTime;
                  //         status = "00";
                  //       }
                  //       _viewModel.saveCommonSettingsByAutoOnOff(context, time, status,
                  //           week, () {
                  //         _viewModel.getTerminalCommonSettings(context);
                  //       });
                  //     });
                  // _toSetAutoOnOffTime();
                }
              },
              child: Visibility(
                visible: StringUtils.isEmpty(autoOnOffTime) || ("00" == _settingsBean?.comAutoSwitch?.autoOnoff),
                child: Image.asset(
                  "images/icon_close.png",
                  width: 36,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  ///音量设置
  Widget _toSetVolumeWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        String onOff = ((_settingsBean?.volume??0)>0)?"00":"01";
        SetTerminalVolumeDialog.navigatorPushDialog(context, onOff, "",
            _settingsBean?.volume, changeVolume: (volume){
              //开关机时间
              _viewModel.saveCommonSettingsByVolume(context,  volume, () {
                _viewModel.getTerminalCommonSettings(context);
              });
            });
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            Text(
              "音量设置",
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                  fontSize: 14
              ),
            ),
            Spacer(),
            Row(
              children: <Widget>[
                Text(
                  (_settingsBean?.volume != null)?"${_settingsBean?.volume}%":"暂未设置",
                  style: TextStyle(
                      color: (_settingsBean?.volume != null)?
                      ThemeRepository.getInstance().getTextMainColor_D0E0F7():
                      ThemeRepository.getInstance()
                          .getTextEditHintColor_3A3F50()
                      ,
                      fontSize: 14
                  ),
                ),
                SizedBox(width: 10,),
                Image.asset(
                  "images/index_arrow_ico.png",
                  width: 6,
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
  ///人脸识别
  Widget _toFaceRecognizeWidget(){
    return Visibility(
      visible: _settingsBean?.isShowFaceRecognition(),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: ()async{
          if((_settingsBean?.licenseActCnt??0) > 0){
            bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: ("00" == _settingsBean?.enableFaceRecognition)?"确定关闭人脸识别功能？":"确定启用人脸识别功能？",
                cancelText: "取消",
                confirmText: ("00" == _settingsBean?.enableFaceRecognition)?"关闭":"开启",
                confirmBgColor: ("00" == _settingsBean?.enableFaceRecognition)?ThemeRepository.getInstance()
                    .getMinorRedColor_F95355(): ThemeRepository.getInstance()
                    .getPrimaryColor_1890FF());
            if (result ?? false) {
              //00启用 01关闭
              _viewModel.saveCommonSettingsByFaceRecognition(context,
                  ("00" == _settingsBean?.enableFaceRecognition)?"01":"00",
                      (){
                    _viewModel.getTerminalCommonSettings(context);
                  }
              );
            }
          }else{
            VgToastUtils.toast(context, "暂无设备支持人脸识别");
          }

        },
        child: Container(
          height: 50,
          alignment: Alignment.centerLeft,
          child: Row(
            children: [
              Text(
                "人脸识别",
                style: TextStyle(
                    color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                    fontSize: 14
                ),
              ),
              SizedBox(width: 10,),
              Text(
                "仅适用支持人脸识别的设备",
                style: TextStyle(
                    color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                    fontSize: 12
                ),
              ),
              Spacer(),
              Image.asset(
                ("00" == _settingsBean?.enableFaceRecognition)
                    ? "images/icon_open.png"
                    :"images/icon_close.png",
                width: 36,
              ),
            ],
          ),
        ),
      ),
    );
  }

  String getWeekAutoOnOffTimeStr(){
    if(_settingsBean?.comAutoSwitch == null){
      return "";
    }
    ComAutoSwitchBean comAutoSwitch = _settingsBean?.comAutoSwitch;
    if("01" == (comAutoSwitch?.autoMon??"") && StringUtils.isNotEmpty(comAutoSwitch?.monTime)){
      return "已启用";
    }
    if("01" == (comAutoSwitch?.autoTues??"") && StringUtils.isNotEmpty(comAutoSwitch?.tuesTime)){
      return "已启用";
    }
    if("01" == (comAutoSwitch?.autoWed??"") && StringUtils.isNotEmpty(comAutoSwitch?.wedTime)){
      return "已启用";
    }
    if("01" == (comAutoSwitch?.autoThur??"") && StringUtils.isNotEmpty(comAutoSwitch?.thurTime)){
      return "已启用";
    }
    if("01" == (comAutoSwitch?.autoFri??"") && StringUtils.isNotEmpty(comAutoSwitch?.friTime)){
      return "已启用";
    }
    if("01" == (comAutoSwitch?.autoSat??"") && StringUtils.isNotEmpty(comAutoSwitch?.satTime)){
      return "已启用";
    }
    if("01" == (comAutoSwitch?.autoSun??"") && StringUtils.isNotEmpty(comAutoSwitch?.sunTime)){
      return "已启用";
    }
    return "";
  }

  String getAutoOffTimeStr(){
    if(_startDateTime == null || _endDateTime == null){
      return null;
    }
    return "${_startDateTime.hour}:${VgToolUtils.twoDigits(_startDateTime.minute)}"
        "-"
        "${_endDateTime.hour}:${VgToolUtils.twoDigits(_endDateTime.minute)}";
  }

  String _getWeekStr(){
    if(StringUtils.isEmpty(_week??"")){
      return "";
    }
    List<String> weekList = _week.split(",");
    String str = "";
    weekList.forEach((element) {
      str += getText(element);
    });
    return str;
  }


  String getText(String index){
    switch (index){
      case "1":
        return "一";
      case "2":
        return "二";
      case "3":
        return "三";
      case "4":
        return "四";
      case "5":
        return "五";
      case "6":
        return "六";
      case "7":
        return "日";
    }
  }
}
